package controllers

import (
	"acs/management/models"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"strconv"

	"github.com/chaosue/echo-sessions"
	"github.com/labstack/echo"
)

func GetTargetListHandler(c echo.Context) (err error) {
	defer models.ErrorHandler(c)
	session := sessions.Default(c)
	manager := session.Get(models.SESSION_USER)
	if manager == nil {
		err = c.Redirect(http.StatusTemporaryRedirect, models.VIEW_LOGIN_URL)
		models.CheckError(err)
	}
	username := c.Param("username")
	var userWithPirvilege models.UserWithPirvilege
	userWithPirvilege.PrivilegeList = models.AllUserPrivilegeList[username]

	var totalNum int64 = -1
	targetStr := c.Param("target")
	var result interface{}
	if targetStr == models.Conf.AcsGroup.Acs_user_group {
		result = models.UserGroup.Members[models.Conf.AcsGroup.Acs_user_group]
	} else if targetStr == "t_app" {
		result, totalNum, err = models.GetAllTApp(nil, nil, nil, nil, 0, 10000, true)
		models.CheckError(err)
	} else if targetStr == "patch" {
		result, _, err = models.GetAllTPatch(nil, nil, nil, nil, 0, 100000, false)
		models.CheckError(err)
	} else if targetStr == "jumei_api" {
		result = models.Conf.JumeiApi.JumeiApiItemList
		totalNum = int64(len(models.Conf.JumeiApi.JumeiApiItemList))
		fmt.Println("totalNum:", totalNum)
		models.CheckError(err)
	}
	c.JSON(http.StatusOK, models.ExportJson(models.Right_Status, userWithPirvilege, result, totalNum))
	return
}

type userPrivilegeObj struct {
	AddPrivilegelist []*models.TPrivilege `json:"addPrivilegelist"`
	CutPrivilegelist []*models.TPrivilege `json:"cutPrivilegelist"`
}

func SaveUserPrivilegeHandler(c echo.Context) (err error) {
	defer models.ErrorHandler(c)
	session := sessions.Default(c)
	manager := session.Get(models.SESSION_USER)
	if manager == nil {
		err = c.Redirect(http.StatusTemporaryRedirect, models.VIEW_LOGIN_URL)
		models.CheckError(err)
	}
	currentUser := models.CheckLogin(c)
	username := c.Param("username")
	if username == "" {
		models.CheckError(errors.New("username 必填"))
	}
	requestbody, requesterr := ioutil.ReadAll(c.Request().Body)
	models.CheckError(requesterr)
	var thisUserPrivilegeObj userPrivilegeObj
	err = json.Unmarshal(requestbody, &thisUserPrivilegeObj)
	models.CheckError(err)
	tablename := ""
	addStr := ""
	for _, item := range thisUserPrivilegeObj.AddPrivilegelist {
		item.Username = username
		addStr += (strconv.Itoa(item.TargetRow) + ":" + item.Action + ";")
		tablename = item.TargetTable
	}
	cutStr := ""
	for _, item := range thisUserPrivilegeObj.CutPrivilegelist {
		item.Username = username
		cutStr += (strconv.Itoa(item.TargetRow) + ":" + item.Action + ";")
	}
	err = models.BatchInsertPrivilege(thisUserPrivilegeObj.AddPrivilegelist)
	models.CheckError(err)
	err = models.BatchRemovePrivilege(thisUserPrivilegeObj.CutPrivilegelist)
	models.CheckError(err)
	var userWithPirvilege models.UserWithPirvilege
	var operationUser models.User
	operationUser.Username = username
	userWithPirvilege.User = operationUser
	models.LoadAllPrivilege()
	userWithPirvilege.PrivilegeList = models.AllUserPrivilegeList[username]
	models.AppendLog(&currentUser, "用户:"+username+".类别："+tablename+".增加:"+addStr+".取消:"+cutStr, models.LOG_TYPE_USER_PRIVILEGE)
	c.JSON(http.StatusOK, models.ExportJson(models.Right_Status, userWithPirvilege, nil, -1))
	return
}
